<template>
    <div class="retrieve-form">
         <div class="title-box">
            <h1>找回密码</h1>
         </div>
        <el-form :model="retrieveform" :rules="rules" ref="retrieveFormRef">
            <div v-if="step === 1">
                <el-form-item prop="account">
                    <el-input v-model="retrieveform.account" type="text" placeholder="用户名" clearable></el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input v-model="retrieveform.password" type="password" placeholder="密码" clearable show-password></el-input>
                </el-form-item>
                <el-form-item prop="confirmPassword">
                    <el-input v-model="retrieveform.confirmPassword" type="password" placeholder="确认密码" clearable show-password></el-input>
                </el-form-item>
            </div>
            <div v-if="step === 2">
                <el-form-item  prop="email">
                    <div class="email-box">
                    <el-input style="width:68%" v-model="retrieveform.email" type="email" placeholder="邮箱" clearable></el-input>
                    <el-button style="width:27%" @click="sendVerificationCode">发送验证码</el-button>
                    </div>
                </el-form-item>
                <el-form-item  prop="inputIdentifyingCode">
                    <el-input style="width:90%" v-model="retrieveform.inputIdentifyingCode" type="text" placeholder="验证码" clearable></el-input>
                </el-form-item>
            </div>
            <div class="button-box" v-if="step === 1">
                <el-button type="primary" @click="goToStep2">下一步</el-button>
                <p @click="switchToLogin">已有账号? 去登录</p>
            </div>
            <div class="button-box" v-if="step === 2">
                <el-button type="primary" @click="completeRetrieve">找回密码</el-button>
                <el-button @click="goBack">返回</el-button>
            </div>
        </el-form>
    </div>
</template>

<script setup>
    import { ref,getCurrentInstance, reactive} from 'vue';
    import { useRouter } from 'vue-router';
    import axios from 'axios';
    import { ElMessage } from 'element-plus';

    const { proxy } = getCurrentInstance();
    const retrieveform = reactive({
        account: '',
        password: '',
        confirmPassword: '',
        email: '',
        inputIdentifyingCode: ''
    });
    const retrieveFormRef = ref();
    const step = ref(1);
    const router = useRouter();

    const rules = {
        account: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 6, max: 16, message: '用户名长度必须在 6 到 16 个字符之间', trigger: ['blur','change']  }
        ],
        password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 16, message: '密码长度必须在 6 到 16 个字符之间', trigger: ['blur','change']  },
             { pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,}$/, message: '密码必须包含字母和数字', trigger:  ['blur','change'] },
        ],
        confirmPassword: [
            { required: true, message: '请确认密码', trigger: 'blur' },
            { validator: (rule, value, callback) => {
                if (value !== retrieveform.password) {
                    callback(new Error('两次输入密码不一致!'));
                } else {
                    callback();
                }
            }, trigger: ['blur','change']  }
        ],
        email: [
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            { type: 'email', message: '邮箱格式不正确', trigger: ['blur','change']  }
        ],
        inputIdentifyingCode: [
            { required: true, message: '请输入验证码', trigger: 'blur' }
        ]
    };

    const switchToLogin = () => {
        router.push('/user/login');
    };
    
    const validateStep1Fields = () => {
        console.log(retrieveFormRef.value)
        console.log(retrieveFormRef.value.account);
        console.log(retrieveform.account)
        return new Promise((resolve, reject) => {
            retrieveFormRef.value.validateField('account', (accountValid) => {
                if (!accountValid) {
                     reject('account');
                }
               retrieveFormRef.value.validateField('password', (passwordValid) => {
                if (!passwordValid) {
                     reject('password');
                }
                retrieveFormRef.value.validateField('confirmPassword', (confirmPasswordValid) => {
                    if (!confirmPasswordValid) {
                    reject('confirmPassword');
                    }
                    resolve();
                });
                });
            });
        });
    };
    //跳转到下一步
    const goToStep2 = async() => {
        try {
            await validateStep1Fields();
            step.value = 2;
        } catch (error) {
            ElMessage.error('请修正表单错误后再继续');
        }
    };

    const goBack = () => {
        step.value = 1; // Move back to step 1
    };

    const sendVerificationCode = async () => {
        await retrieveFormRef.value.validateField('email',async(emailValid)=>{
            if(emailValid){
                await proxy.$http.post('/pass_back/', {
                    type:'sendVerificationCode',
                    'user_name': retrieveform.account,
                    'pass_word': retrieveform.password,
                    'pass_ensure': retrieveform.confirmPassword, 
                    'email': retrieveform.email
                }).then((res)=>{
                        if(res.data.status=="success"){
                            ElMessage.success('验证码已发送到您的邮箱');
                        }else{
                            ElMessage.error(res.data.message);
                        }
                }).catch((err)=>{
                    ElMessage.error('发送验证码请求失败');
                });
            } else {
                ElMessage.error('请修正邮箱错误后再尝试发送验证码');
            }
        })
    };

    const completeRetrieve = async () => {
      await retrieveFormRef.value.validateField('inputIdentifyingCode',async(inputIdentifyingCodeValid)=>{
            if (inputIdentifyingCodeValid) {
                    await proxy.$http.post('/pass_back/', {
                            type:'passback',
                            user_name:retrieveform.account,
                            code:retrieveform.inputIdentifyingCode
                    }).then((res)=>{
                            if(res.data.status=="success"){
                                router.push('/user/login');
                                ElMessage.success('修改密码成功');
                            }else{
                                ElMessage.error(res.data.message);
                            }
                    }).catch((err)=>{
                        ElMessage.error('请求失败，请稍后重试');
                    });
            }else{
                ElMessage.error('请输入验证码');
            }
      })
    };
</script>

<style scoped>
 
    .retrieve-form {
        height: 100%;
        width: 50%;
        position: absolute;
        top: 0;
        left: 0;
        display: flex;
        flex-direction: column;
        align-items: center;
    }
     .title-box {
        margin-top: 25%;
        margin-bottom: 10%;
    }
    .title-box h1{
        text-align: center;
        align-items: center;
        letter-spacing: 5px;
        color: white;
        text-shadow:4px 4px 3px rgba(0,0,0,.1);
        font-size: 25px;
    }
    .el-form{
        width: 60%;
    }
    .button-box{
        display: flex;
        justify-content: center;
        align-items: center; 
    }
    .el-input{   
        height: 100%;
        text-indent: 4px;
        border: 1px solid #b0cfe9;
    }
    button{
        width:100px;
        height: 30px;
        line-height: 30px;
        border: none;
        border-radius: 4px;
        background-color: #69b3f0;
        color: white;
        margin-right: 5px;
    }
    .button-box p{
        color: white;
    }
    .button-box p:hover{
        cursor: pointer;
    }
    .email-box{
        width: 100%;
        display: flex;
        align-items: center;
        gap: 10px;
    }
</style>